<template>
  <div>
    <div class="container">
      <div class="handle-box">
        <el-select
          v-model="query.matchType"
          placeholder="比赛类型"
          class="handle-select mr10"
        >
        <el-option key="1" label="全部" value=""></el-option>
          <el-option key="2" label="TPP模式" value="TPP"></el-option>
          <el-option key="3" label="FPP模式" value="FPP"></el-option>
        </el-select>
        <el-select
          v-model="query.matchState"
          placeholder="比赛状态"
          class="handle-select mr10"
        >
        <el-option key="1" label="全部" value=""></el-option>
          <el-option key="2" label="进行中" value="1"></el-option>
          <el-option key="3" label="未开始" value="2"></el-option>
          <el-option key="4" label="已结束" value="3"></el-option>
        </el-select>
        <el-input
          v-model="query.search"
          placeholder="比赛名称"
          class="handle-input mr10"
        ></el-input>
        <el-button type="primary" :icon="Search" @click="handleSearch"
          >搜索</el-button
        >
        <el-button type="primary" :icon="Plus" @click="ClickAdd"
          >新增</el-button
        >
      </div>
      <el-table
        :data="tableData"
        border
        class="table"
        ref="multipleTable"
        header-cell-class-name="table-header"
      >
        <el-table-column
          type="index"
          :index="table_index"
          label="序号"
          width="55"
          align="center"
        ></el-table-column>
        <el-table-column label="状态" align="center" width="90">
          <template #default="scope">
            <el-tag
              :type="
                scope.row.status === 1
                  ? 'success'
                  : scope.row.status === 2
                  ? 'warning'
                  : scope.row.status === 3
                  ? 'info'
                  : ''
              "
            >
              {{
                scope.row.status === 1
                  ? "进行中"
                  : scope.row.status === 2
                  ? "未开始"
                  : scope.row.status === 3
                  ? "已结束"
                  : ""
              }}
            </el-tag>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="id" label="ID" hidden=true  width="0" align="center"></el-table-column> -->
        <el-table-column prop="types" align="center" label="比赛模式" width="130">
          <template #default="scope">
            {{
              scope.row.model === "TPP"
                ? "第三人称TPP"
                : scope.row.model === "FPP"
                ? "第一人称FPP"
                : "待定"
            }}
          </template>
        </el-table-column>
        <el-table-column
          prop="matchName"
          align="center"
          label="比赛名称"
          width="420"
        ></el-table-column>
        <el-table-column
          prop="matchCode"
          align="center"
          label="比赛编码"
        ></el-table-column>
        <el-table-column label="队伍数" align="center" width="80" type="success">
          <template #default="scope" >
            <el-button
              text
              width="40"
              @click="handleTeam(scope.$index, scope.row)"
              v-permiss="20"
              style="color:steelblue;font-size: 20px;font-weight: bold;"
            >
           {{ scope.row.teamNum}}
          </el-button>
          </template>
        </el-table-column>
        <el-table-column label="报名表" align="center" width="80" type="success">
          <template #default="scope" >
            <el-button
              text
              width="40"
              @click="handleTable(scope.$index, scope.row)"
              v-permiss="20"
            >
            <i class="el-icon-lx-calendar"></i>
          </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="startTime" width="180" label="开始时间"></el-table-column>
        <el-table-column prop="endTime"  width="180" label="结束时间"></el-table-column>
        <el-table-column label="操作" width="160" align="center">
          <template #default="scope">
            <el-button
              text
              :icon="Edit"
              width="40"
              @click="handleEdit(scope.$index, scope.row)"
              v-permiss="20"
            >
            </el-button>
            <el-button
              text
              :icon="Delete"
              class="red"
              @click="handleDelete(scope.row.matchCode)"
              v-permiss="16"
            >
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          background
          layout="total,sizes, prev, pager, next"
          v-model:page-size="query.limit"
          :page-sizes="[10, 15, 20, 50]"
          :current-page="query.page"
          :total="pageTotal"
          :hide-on-single-page="false"
          @current-change="handlePageChange"
          @size-change="handleSizeChange"
        ></el-pagination>
      </div>
    </div>
    <!-- 编辑比赛信息 -->
    <el-dialog title="编辑" v-model="editVisible" v-if="editVisible" :before-close="dialogClose(1)" width="28%">
      <el-form label-width="70px" >
        <el-form-item label="比赛编码">
          <el-input v-model="form.matchCode" disabled width="20px"></el-input>
        </el-form-item>
        <el-form-item label="比赛名称">
          <el-input v-model="form.matchName" width="40px"></el-input>
        </el-form-item>
        <el-form-item label="比赛模式">
          <el-select
            v-model="form.model"
            placeholder="比赛模式"
            :no-data-text="form.model"
            class="handle-select mr10"
          >
            <el-option key="1" label="TPP模式" value="TPP"></el-option>
            <el-option key="2" label="FPP模式" value="FPP"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="比赛时间" >
          <el-date-picker  width="100px"
      v-model="form.selectTime"
      type="datetimerange"
      value-format="YYYY-MM-DDTHH:mm:ssZ"
      start-placeholder="开始时间"
      end-placeholder="结束时间"
      :default-time="defaultTime2"
    />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveEdit">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 成员查看框 -->
    <el-dialog title="参数队伍管理" v-if="editvisitTeam" v-model="editvisitTeam" width="40%">
      <el-form label-width="70px">
        <el-form-item label="比赛场次">
          <el-input v-model="teamForm.matchName" disabled></el-input>
        </el-form-item>
      </el-form>
      <el-transfer
      v-model="teamValue"
      style="text-align: left; display: inline-block"
      filterable
      :render-content="renderFunc"
      :titles="['战队库', '参赛队伍']"
      :button-texts="['移除', '添加']"
      :format="{
        noChecked: '${total}',
        hasChecked: '${checked}/${total}',
      }"
      :data="allTeam"
      @change="handleChange"
    >
  </el-transfer>

    </el-dialog>

    <!-- 新增战队 -->
    <el-dialog title="编辑" v-model="addVisible" v-if="addVisible" :before-close="dialogClose(2)" width="30%">
      <el-form label-width="70px" ref="refaddform">
        <el-form-item label="比赛编码">
          <el-input v-model="form.matchCode"  width="20px"></el-input>
        </el-form-item>
        <el-form-item label="比赛名称">
          <el-input v-model="form.matchName" width="40px"></el-input>
        </el-form-item>
        <el-form-item label="比赛模式">
          <el-select
            v-model="form.model"
            placeholder="比赛模式"
            :no-data-text="form.model"
            class="handle-select mr10"
          >
            <el-option key="1" label="TPP模式" value="TPP"></el-option>
            <el-option key="2" label="FPP模式" value="FPP"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="比赛时间" >
          <el-date-picker  width="100px"
      v-model="form.selectTime"
      type="datetimerange"
      value-format="YYYY-MM-DDTHH:mm:ssZ"
      start-placeholder="开始时间"
      end-placeholder="结束时间"
      :default-time="defaultTime2"
    />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addVisible = false">取 消</el-button>
          <el-button type="primary" @click="AddEdit">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="matchtable">
import { ref, reactive, unref } from "vue";
import VueCropper from "vue-cropperjs";
import { AxiosRequestConfig } from "axios";
import { ElMessage, ElMessageBox } from "element-plus";
import { Delete, Edit, Search, Plus } from "@element-plus/icons-vue";
import Editimg from "./editimg.vue";
import "cropperjs/dist/cropper.css";
import {
  GetMatchList,
  GetMatchTeamList,
  GetMatchTeamUnList,
  AddMatch,
  EditMatch,
  DeleMatch,
  EditMatchTeam,
} from "../api/match";
import { el } from "element-plus/es/locale";
import type { VNode, VNodeProps } from 'vue'

// 参数队伍功能
const teamValue =ref<string[]>([]);

interface Option {
  key: string
  label: string
  disabled: boolean
}
let teamForm = reactive({
  matchName:'',
	matchCode: '',
  appTeam:[''],

});
const handleChange = (
  value: number | string,
  direction: 'left' | 'right',
  movedKeys: string[] | number[]
) => {
   EditMatchTeam(value,teamForm.matchCode).then((res:any) => {
      if (res.data.code === 200 ) {
        ElMessage.success(res.data.msg);
      } else {
        ElMessage.error(res.data.msg);
      }
    })
    .catch((res) => {
      console.log(res)
    });
  console.log(value)
}
const renderFunc = (
  h: (type: string, props: VNodeProps | null, children?: string) => VNode,
  option: Option
) => {
  return h('span', null, option.label)
}
const getMatchTeamList = (matchCode:string)=>{
  teamValue.value=[]
  GetMatchTeamList(matchCode)
    .then((res:any) => {
      if (res.data.code === 200 ) {
        
		    teamValue.value.push(...res.data.data)
        
      } else {
        ElMessage.error(res.data.msg);
      }
    })
    .catch((res) => {
      console.log(res)
    });
    editvisitTeam.value = true;
}
const getMatchTeamUnList = ()=>{
  const data: Option[] = []
  GetMatchTeamUnList("")
    .then((res:any) => {
      if (res.data.code === 200 ) {
		    data.push(...res.data.data)
      } else {
        ElMessage.error(res.data.msg);
      }
    })
    .catch((res) => {
      console.log(res)
    });
   return data
}
const allTeam = ref<Option[]>(getMatchTeamUnList())
const handleTeam = (index: number, row: any) => {
 
  getMatchTeamList(row.matchCode)
 idx = index;
 teamForm.matchCode=row.matchCode
 teamForm.matchName = row.matchName;
 
};


//分割线
interface LinkItem {
  value: string;
  key: string;
}
const defaultTime2: [Date, Date] = [
  new Date(2023, 1, 1, 12, 0, 0),
  new Date(2023, 2, 1, 23, 59, 59),
] // '12:00:00', '08:00:00'
const links = ref<LinkItem[]>([]);

interface TableItem {
  id: number;
  name: string;
  thum: string;
  number: number;
  status: number;
  types: string;
  captain: string;
  model: string;
  CreatedTime: string;
  UpdateTime: string;
}
interface Player {
  id: number;
  name: string;
  money: string;
  state: string;
  date: string;
  captain: string;
}


const query = reactive({
  matchType: "",
  matchState: "",
  search: "",
  sortBy:"id",
  total: 15,
  page: 1,
  limit: 10,
});
const dialogQuery = reactive({
  matchCode: "",
  types: "",//app 报名 entry 参赛
  search: "",
  total: 15,
  page: 1,
  limit: 10,
});
const tableData = ref<TableItem[]>([]);
const pageTotal = ref(0);

// 表格编辑时弹窗和保存
const editVisible = ref(false);
const editvisitTeam = ref(false);
const visitTeam = ref(false);
const addVisible = ref(false);
let form = reactive({
  matchCode:'',
	matchName: '',
  model: '',
  selectTime:[''],
  startTime:'',
  endTime:'',
});



// 自动补全
const querySearchAsync = (queryString: string, cb: (arg: any) => void) => {
  const results = queryString
    ? links.value.filter(createFilter(queryString))
    : links.value;
  cb(results);
};
const createFilter = (queryString: string) => {
  return (restaurant: LinkItem) => {
    return (
      restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
    );
  };
};
// 搜索
const handleSelect = (item: LinkItem) => {
  console.log(item);
};
// 获取表格数据
const init = async () => {
  let urlparm = {
    matchType: query.matchType,
    matchState: query.matchState,
    sortBy:query.sortBy,
    search: query.search,
    page: query.page,
    limit: query.limit,
  };
  const { data }:any = await GetMatchList(urlparm);

  tableData.value = data.data;
  pageTotal.value = data.total;

  // pageTotal.value = 15;
};
init();
// 查询操作
const handleSearch = () => {
  query.page = 1;
  init();
};
// 分页导航
const handlePageChange = (val: number) => {
  query.page = val;
  init();
};
const handleSizeChange = (val: number) => {
  query.limit = val;
  init();
};
const table_index = (index: number) => {
  return (query.page - 1) * query.limit + index + 1;
};

// 弹窗分页导航
const dialoghandlePageChange = (val: number) => {
  dialogQuery.page = val;
  init();
};

const entryTime = (value:string) =>{
  console.log(value)
  console.log(form.startTime)
}

const dialogClose = (types:number)=>{
 
  //编辑
  if(types==1){
    addVisible.value=false
  }else if(types==2){
    editVisible.value=false
  }
}
// 删除操作
const handleDelete = (matchCode: string) => {
  // 二次确认删除
  ElMessageBox.confirm("确定要删除吗？", "提示", {
    type: "warning",
  })
    .then(() => {
      DeleMatch(matchCode)
        .then((res:any) => {
          if (res.data.code === 200) {
            ElMessage.success("删除成功");
            init();
          } else {
            ElMessage.error(res.data.msg);
          }
        })
        .catch((res) => {
          ElMessage.error(res.data.msg);
        });
      
    })
    .catch(() => {});
};

let idx: number = -1;
const handleEdit = (index: number, row: any) => {
 
  idx = index;
  form.matchCode=row.matchCode
  form.matchName = row.matchName;
  form.model = row.model;
  form.selectTime=[row.startTime,row.startTime];
  

  editVisible.value = true;
};

const handleTable = (index: number, row: any) => {
 
  idx = index;
  form.matchCode=row.matchCode
  form.matchName = row.matchName;
  form.model = row.model;
  form.selectTime=[row.startTime,row.startTime];
  

  editVisible.value = true;
};
//编辑战队
const saveEdit = () => {
  form.startTime=form.selectTime[0]
  form.endTime=form.selectTime[1]
  EditMatch(form,form.matchCode)
    .then((res:any) => {
      if (res.data.code === 200 ) {
        ElMessage.success(`修改比赛信息成功`);
        editVisible.value = false;
		init()
      } else {
        ElMessage.error(res.data.msg);
      }
    })
    .catch((res) => {
      ElMessage.error(res.data.msg);
    });
};
//添加战队
let refaddform = ref()

const ClickAdd = ()=>{

	addVisible.value=true;
	
  form.matchCode=''
  form.matchName = '';
  form.model = '';
  form.selectTime=['',''];

}
const AddEdit = () => {
  // console.log(value);
  form.startTime=form.selectTime[0]
  form.endTime=form.selectTime[1]
  AddMatch(form)
    .then((res:any) => {
      if (res.data.code === 200 ) {
        init();
        ElMessage.success("添加成功");
		   addVisible.value = false;
	  	  const reset=unref(refaddform)
	      reset.value.resetFields();
		    
      } else {
        ElMessage.error(res.data.msg);
      }
    })
    .catch((res) => {
      ElMessage.error(res.data.msg);
    });

 
};
</script>

<style scoped>
.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
}
.table {
  width: 100%;
  font-size: 14px;
}
.red {
  color: #f56c6c;
}
.mr10 {
  margin-right: 10px;
}
.table-td-thumb {
  display: block;
  margin: auto;
  width: 40px;
  height: 40px;
}
</style>
